<?php

namespace App\Clients;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Storage;
use Psr\Http\Message\ResponseInterface;

class BaseClient
{
    public $client;
    public $cookieJar;

    public function cookiePath(): string
    {
        $name = $this->account['username'];
        return Storage::disk('public')->path("cookies/red-book-{$name}-cookies.json");
    }

    public function getCookieJar()
    {
        if (!$this->cookieJar) {
            $path = $this->cookiePath();

            if ($path) {
                return new FileCookieJar($path, true);
            }
            return true;
        }
        return $this->cookieJar;
    }


    /**
     * 获取Request Client
     * @param array $headers
     * @param array $config
     * @return Client
     */
    public function getClient($headers = [], $config = [])
    {
        if (!$this->client) {
            $cookieJar = $this->getCookieJar();
            $ip = '120.192.203.14';
            $headers = array_merge([
                'Content-Type' => 'application/json;charset=UTF-8',
                'Accept' => 'application/json, text/javascript, */*; q=0.01',
                'CLIENT-IP' => $ip,
                'X-FORWARDED-FOR' => $ip,
            ], $headers);

            $config = array_merge([
                'verify' => false,
                'http_errors' => false,
                'cookies' => $cookieJar,
                'headers' => $headers,
                'timeout' => 6000,
            ], $config);


            $this->client = new Client($config);
        }

        return $this->client;
    }

    public function request($method, $url, $config)
    {
        try {
            $client = $this->getClient();
            $guzzleResult = $client->request($method, $url, $config);
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            $guzzleResult = $e->getResponse();
        }
        return $guzzleResult;

    }

    /**
     * get 请求方法
     * @param $url
     * @param array $query
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function get($url, array $query = [])
    {
        return $this->request('GET', $url, $query);
    }

    public function post($url, $query = [])
    {
        return $this->request('POST', $url, $query);
    }
}
